#!/bin/bash

GPG_CONFIG=/usr/share/gentoo-syncer/gpg
MY_TMPDIR=/var/tmp/gentoo-syncer

set -e
shopt -s nullglob

error() {
        echo "Error: $*"
        cleanup
}

cleanup() {
        rm -rf "$MY_TMPDIR"/*
}

trap "error Signal caugth" SIGINT SIGTERM
trap "cleanup" EXIT

if [ "$1" = "--help" ]; then
        echo "Usage: $0 <sync_dir> gentoo://<portage_file_url>"
        exit 0
fi

SYNC_DIR="$1"
GENTOO_URL="$2"

if ! [[ ${GENTOO_URL} =~ ^gentoo://(.*)$ ]]; then
        echo "Wrong URL"
        exit 1
fi

PORTAGE_URL="${BASH_REMATCH[1]}"
PORTAGE_URL_SIGN="${PORTAGE_URL}.gpgsig"

echo "Sync: $SYNC_DIR from $PORTAGE_URL sign $PORTAGE_URL_SIGN"

cleanup

cp -r "$GPG_CONFIG" "$MY_TMPDIR/gpg"

mkdir "$MY_TMPDIR/download"
cd "$MY_TMPDIR/download"

wget "$PORTAGE_URL" -O portage-latest.tar.xxx
wget "$PORTAGE_URL_SIGN" -O portage-latest.tar.xxx.asc

GNUPGHOME="$MY_TMPDIR/gpg" gpg --verify portage-latest.tar.xxx.asc

mkdir "$MY_TMPDIR/extract"
cd "$MY_TMPDIR/extract"
tar xf "$MY_TMPDIR/download/portage-latest.tar.xxx"

rsync --recursive --links --safe-links --perms --times \
        --force --whole-file --delete --stats \
        --exclude=/distfiles --exclude=/local --exclude=/packages \
        --verbose \
        "$MY_TMPDIR/extract/portage/" "$SYNC_DIR"

echo Done
